package visualizer.google;

import java.io.IOException;
import java.net.Socket;
import java.net.URL;

import processing.core.PApplet;

public class IpAddressRetriever {
	private PApplet context;
	
	public IpAddressRetriever(PApplet context)
	{
		this.context = context;
	}
	
	/**
	 * Attempts to retrieve the IP address a PApplet is being run from
	 * 
	 * @return the IP address or null if unable to retrieve
	 */
	public String get()
	{
		URL base = context.getDocumentBase();
		
		int port = base.getPort();
		if (port == -1) {
			port = 80;
		}
		
		try {
			Socket s = new Socket(base.getHost(), port);
			return s.getLocalAddress().getHostAddress();
		} catch (IOException e) {
			return null;
		}
	}
}
